package com.tul.exercise.base.thread.base;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 捕获并处理线程异常
 */
public class CaptureUncaughtException {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory());

        exec.execute(new ExceptionThread2());
    }
}

/**
 * 抛出异常线程
 */
class ExceptionThread2 implements Runnable {

    @Override
    public void run() {
        Thread t = Thread.currentThread();
        System.out.println("run() by " + t);
        // 打印线程的异常处理类
        System.out.println("eh=" + t.getUncaughtExceptionHandler());
        throw new RuntimeException();
    }
}

/**
 * 处理线程异常的类
 */
class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.out.println("原因 " + e);
    }
}

/**
 * 线程工程类
 */
class HandlerThreadFactory implements ThreadFactory {

    @Override
    public Thread newThread(Runnable r) {
        System.out.println(this + " 正在创建新线程...");
        Thread t = new Thread(r);
        System.out.println("创建线程 " + t);

        // 设置线程异常处理类
        t.setUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
        System.out.println("eh=" + t.getUncaughtExceptionHandler());
        return t;
    }
}
